package com.koron.operation.classes.form.controller;


import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.WorkflowController;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.operation.classes.form.bean.constants.ClassesFormUtil;
import com.koron.operation.classes.form.bean.dto.ClassesFormClockIn;
import com.koron.operation.classes.form.bean.dto.ClassesFormDTO;
import com.koron.operation.classes.form.bean.dto.ClassesFormRankDTO;
import com.koron.operation.classes.form.bean.query.ClassesFormQuery;
import com.koron.operation.classes.form.bean.vo.ClassesFormVO;
import com.koron.operation.classes.form.excel.ClassesFormListener;
import com.koron.operation.classes.form.excel.ClassesFormWriteHandler;
import com.koron.operation.classes.form.service.ClassesFormService;
import com.koron.operation.classes.info.service.ClassesClassifyService;
import com.koron.operation.classes.shift.bean.dto.ChangeShiftDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 月度排班表(ClassesForm)表控制层
 *
 * @author jzp
 * @since 2023-05-17 09:43:29
 */
@Api(tags = "月度排班表接口")
@RestController
@RequestMapping("classesForm")
public class ClassesFormController implements WorkflowController {
    /**
     * 服务对象
     */
    @Autowired
    private ClassesFormService classesFormService;
    @Autowired
    private ClassesClassifyService classesClassifyService;

    @Autowired
    private WorkFlowHandler workFlowHandler;

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    // 数据模拟，查询水产下的人
    @ApiOperation(value = "查询水产下的人")
    @GetMapping("getUserListByOrgId")
    public Response<List<ClassesFormRankDTO>> getUserListByOrgId(@RequestParam String orgId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), classesFormService, "getUserListByOrgId", List.class, orgId));
    }

    @ApiOperation(value = "分页")
    @GetMapping("page")
    public Response<PageInfo<ClassesFormVO>> page(PageQuery pageQuery, ClassesFormQuery query) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), classesFormService, "page", PageInfo.class, pageQuery, query));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询详情")
    @GetMapping("detail")
    public Response<ClassesFormDTO> selectDetail(@RequestParam String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), classesFormService, "getDtoById", ClassesFormDTO.class, id));
    }

    @ApiOperation(value = "获取打卡面板")
    @GetMapping("info")
    public Response<ClassesFormClockIn> info(String deptId, String account, Date date) {
        if (deptId == null) {
            deptId = ThreadLocalContext.get().getOrgId();
        }
        if (account == null) {
            account = ThreadLocalContext.get().getAccount();
        }
        if (date == null) {
            date = DateUtil.parseDate(DateUtil.today());
        }
        return Response.ok(ADOConnection.runTask(getCurrDs(), classesFormService, "info", ClassesFormClockIn.class, deptId, account, date));
    }

    @ApiOperation(value = "获取班次信息")
    @GetMapping("shiftInfo")
    public Response<ChangeShiftDTO> shiftInfo(@RequestParam("deptId") String deptId, @RequestParam("rankId") String rankId, @RequestParam("date") Date date) {
        if (deptId == null) {
            deptId = ThreadLocalContext.get().getOrgId();
        }
        if (date == null) {
            date = DateUtil.date();
        }
        return Response.ok(ADOConnection.runTask(getCurrDs(), classesFormService, "shiftInfo", ChangeShiftDTO.class, deptId, rankId, date));
    }

    @ApiOperation(value = "保存或更新数据")
    @PostMapping
    public Response<ClassesFormDTO> save(@RequestBody ClassesFormDTO dto) {
        ADOConnection.runTask(getCurrDs(), classesFormService, "saveDto", Boolean.class, dto);
        return Response.ok(dto);
    }

    @ApiOperation(value = "删除数据")
    @DeleteMapping
    public Response<String> delete(@RequestParam String id) {
        ADOConnection.runTask(getCurrDs(), classesFormService, "deleteById", Boolean.class, id);
        workFlowHandler.delete(id);
        return Response.ok();
    }

    @Override
    public Response<Object> updateState(@RequestBody RedirectQuery redirectQuery) {
        ClassesFormDTO classesFormDTO = JSON.parseObject(redirectQuery.getFormVariables(), ClassesFormDTO.class);
        if (redirectQuery.getOperation() == 16) {
            // 如果是废弃，状态改为草稿，并删除流程
            ADOConnection.runTask(getCurrDs(), classesFormService, "updateStatus", Boolean.class, redirectQuery.getDataId(), ClassesFormUtil.Status.DRAFT);
            workFlowHandler.delete(redirectQuery.getDataId());
        } else {
            ADOConnection.runTask(getCurrDs(), classesFormService, "submit", Boolean.class, classesFormDTO, redirectQuery.getCurNodeCode());
        }
        return Response.success();
    }

    @SneakyThrows
    @ApiOperation(value = "下载模板")
    @GetMapping("template")
    public void template(String id, HttpServletResponse response) {
        ClassesFormDTO classesFormDTO = ADOConnection.runTask(getCurrDs(), classesFormService, "getDtoById", ClassesFormDTO.class, id);
        String path = "excel/shiftForm.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        String fileName = URLEncoder.encode(classesFormDTO.getName(), "UTF-8").replaceAll("\\+", "%20");
        wrapExcelResponse(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .withTemplate(classPathResource.getInputStream())
                .inMemory(true)
                .registerWriteHandler(new ClassesFormWriteHandler(false, classesFormService, classesFormDTO))
                .sheet()
                .doWrite(Collections.emptyList());
    }

    @SneakyThrows
    @ApiOperation(value = "导出")
    @GetMapping("export")
    public void exportFile(String id, HttpServletResponse response) {
        ClassesFormDTO classesFormDTO = ADOConnection.runTask(getCurrDs(), classesFormService, "getDtoById", ClassesFormDTO.class, id);
        String path = "excel/shiftForm.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        String fileName = URLEncoder.encode(classesFormDTO.getName(), "UTF-8").replaceAll("\\+", "%20");
        wrapExcelResponse(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .withTemplate(classPathResource.getInputStream())
                .inMemory(true)
                .registerWriteHandler(new ClassesFormWriteHandler(true, classesFormService, classesFormDTO))
                .sheet()
                .doWrite(Collections.emptyList());
    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("import")
    public Response importFile(String id, @RequestParam("file") MultipartFile file) {
        EasyExcel.read(file.getInputStream(), new ClassesFormListener(id, classesFormService, classesClassifyService))
                .sheet()
                .headRowNumber(0)
                .doRead();
        return Response.ok("导入成功", null);
    }

    private void wrapExcelResponse(HttpServletResponse response, String fileName) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

}
